from typing import List, Dict
from app.models.chapter import Chapter
from app.models.question import Question, QuestionSource, QuestionStatus
from app.services.llm_service import LLMService


class QuestionService:
    """题目生成服务"""
    
    def __init__(self):
        self.llama_service = LLMService()
    
    async def generate_questions_from_chapter(
        self,
        chapter_id: int,
        question_types: List[str],
        difficulty: str,
        num_questions: int = 5
    ) -> List[Question]:
        """基于章节内容生成题目"""
        # 获取章节内容
        chapter = await Chapter.get(id=chapter_id).prefetch_related('content')
        if not chapter.content:
            raise ValueError("章节内容不存在")

        questions_data = await self.llama_service.generate_questions_from_text(
            text=chapter.content.processed_content or chapter.content.content,
            question_types=question_types,
            difficulty=difficulty,
            num_questions=num_questions
        )
        
        # 创建题目
        questions = []
        for q_data in questions_data["questions"]:
            # 创建题目
            question = await Question.create(
                subject_id=chapter.document.subject_id,
                chapter_id=chapter_id,
                title=q_data["title"],
                content=q_data["content"],
                type=q_data["type"],
                difficulty=q_data["difficulty"],
                answer=q_data["answer"],
                analysis=q_data["analysis"],
                reference=q_data["reference"],
                status=QuestionStatus.DRAFT
            )
            
            # 创建题目来源
            await QuestionSource.create(
                question_id=question.id,
                chapter_content_id=chapter.content.id,
                content=q_data["reference"],
                position=q_data["source_position"]
            )
            
            questions.append(question)
            
        return questions 

    async def generate_questions_batch(
        self,
        chapter_ids: List[int],
        question_types: List[str],
        difficulty: str,
        num_questions_per_chapter: int = 5,
        max_concurrent: int = 3
    ) -> Dict[int, List[Question]]:
        """批量生成题目
        
        Args:
            chapter_ids: 章节ID列表
            question_types: 题目类型列表
            difficulty: 难度级别
            num_questions_per_chapter: 每个章节生成的题目数量
            max_concurrent: 最大并发数
        
        Returns:
            Dict[int, List[Question]]: 按章节ID组织的题目列表
        """
        # 获取所有章节内容
        chapters = await Chapter.filter(
            id__in=chapter_ids
        ).prefetch_related('content', 'document')
        
        if not chapters:
            raise ValueError("未找到指定的章节")
            
        # 准备文本数据
        texts = [
            {
                "id": str(chapter.id),
                "text": chapter.content.processed_content or chapter.content.content
            }
            for chapter in chapters
            if chapter.content
        ]
        
        # 批量生成题目
        questions_data = await self.llama_service.generate_questions_batch(
            texts=texts,
            question_types=question_types,
            difficulty=difficulty,
            num_questions_per_text=num_questions_per_chapter,
            max_concurrent=max_concurrent
        )
        
        # 保存题目
        result = {}
        for chapter in chapters:
            chapter_id = str(chapter.id)
            if chapter_id not in questions_data:
                continue
                
            questions = []
            for q_data in questions_data[chapter_id]["questions"]:
                # 创建题目
                question = await Question.create(
                    subject_id=chapter.document.subject_id,
                    chapter_id=chapter.id,
                    title=q_data["title"],
                    content=q_data["content"],
                    type=q_data["type"],
                    difficulty=q_data["difficulty"],
                    answer=q_data["answer"],
                    analysis=q_data["analysis"],
                    reference=q_data["reference"],
                    status=QuestionStatus.DRAFT
                )
                
                # 创建题目来源
                await QuestionSource.create(
                    question_id=question.id,
                    chapter_content_id=chapter.content.id,
                    content=q_data["reference"],
                    position=q_data["source_position"]
                )
                
                questions.append(question)
            
            result[chapter.id] = questions
            
        return result 